import axios from 'axios'
import type { AxiosInstance, AxiosResponse, AxiosError } from 'axios'

// 定义接口响应数据的类型
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 定义登录接口的请求参数类型
interface LoginParams {
  account: string
  password: string
}

// 定义登录接口的响应数据类型
interface LoginResponse {
  token: string
  userInfo: {
    account: string
    nickname: string
  }
}

const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 使用环境变量
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use((config) => {
  const auth = localStorage.getItem('auth')
  if (auth) {
    const token = JSON.parse(auth).token
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    if (response.data.code !== 200) {
      return Promise.reject(response.data.message)
    }
    return response.data.data
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  },
)

export const login = (params: LoginParams): Promise<LoginResponse> => {
  return api.post('/auth/login', params)
}
